package com.bc.plugin.doc.resolver.param;

import com.bc.plugin.doc.dto.FieldClassDTO;
import com.bc.plugin.doc.resolver.IApiParamHandle;
import com.power.common.util.StringUtil;
import com.power.doc.constants.DocAnnotationConstants;
import com.power.doc.model.ApiParam;
import com.power.doc.utils.DocClassUtil;
import com.thoughtworks.qdox.model.DocletTag;
import com.thoughtworks.qdox.model.JavaAnnotation;

import java.util.List;

public class AnnotationApiParamHandle implements IApiParamHandle {

    @Override
    public ApiParam handle(ApiParam apiParam, FieldClassDTO fieldClassDTO, boolean isResponse) {
        List<JavaAnnotation> javaAnnotations = fieldClassDTO.getJavaField().getAnnotations();
        int annotationCounter = 0;
        an:
        for (JavaAnnotation annotation : javaAnnotations) {
            String annotationName = annotation.getType().getSimpleName();
            if (DocAnnotationConstants.SHORT_JSON_IGNORE.equals(annotationName) && isResponse) {
                return null;
            } else if (DocAnnotationConstants.SHORT_JSON_FIELD.equals(annotationName) && isResponse) {
                if (null != annotation.getProperty(DocAnnotationConstants.SERIALIZE_PROP)) {
                    if (Boolean.FALSE.toString().equals(annotation.getProperty(DocAnnotationConstants.SERIALIZE_PROP).toString())) {
                        return null;
                    }
                } else if (null != annotation.getProperty(DocAnnotationConstants.NAME_PROP)) {
                    apiParam.setField(StringUtil.removeQuotes(annotation.getProperty(DocAnnotationConstants.NAME_PROP).toString()));
                }
            } else if (DocAnnotationConstants.SHORT_JSON_PROPERTY.equals(annotationName) && isResponse) {
                if (null != annotation.getProperty(DocAnnotationConstants.VALUE_PROP)) {
                    apiParam.setField(StringUtil.removeQuotes(annotation.getProperty(DocAnnotationConstants.VALUE_PROP).toString()));
                }
            } else if (DocClassUtil.isJSR303Required(annotationName)) {
                apiParam.setRequired(true);
                annotationCounter++;
                break an;
            }
        }
        if (annotationCounter < 1) {
            List<DocletTag> paramTags = fieldClassDTO.getJavaField().getTags();
            for (DocletTag docletTag : paramTags) {
                if (DocClassUtil.isRequiredTag(docletTag.getName())) {
                    apiParam.setRequired(true);
                }
            }
        }
        return apiParam;
    }
}
